import { Client } from '@stomp/stompjs'
import SockJS from 'sockjs-client' // 添加这行导入
import { getToken, getTokenB } from './auth'
import { useUserStore } from '../store/user'
import { ElNotification } from 'element-plus'

export interface WebSocketMessage {
  id: number
  userId: number
  title: string
  description: string
  type: string
  nextRemindTime: string
  status: string
  advanceMinutes?: number
}

// 新增：健康状态消息接口
export interface HealthMessage {
  userId: number
  robotId?: string
  status: string
  message: string
  timestamp: string
}

export class WebSocketService {
  private client: Client | null = null
  private isConnected = false
  private subscriptions: Map<string, any> = new Map()
  private reconnectAttempts = 0
  private maxReconnectAttempts = 5
  private reconnectDelay = 3000
  private autoConnectOnInit = true // 新增：是否在初始化时自动连接

  constructor() {
    this.client = new Client({
      brokerURL: undefined, // 将通过SockJS连接
      connectHeaders: {},
      // debug: (str) => {
      //   console.log('STOMP Debug:', str)
      // },
      reconnectDelay: this.reconnectDelay,
      heartbeatIncoming: 4000,
      heartbeatOutgoing: 4000
    })

    this.setupEventHandlers()

    // 页面加载时检查是否需要自动连接
    this.checkAutoConnect()
  }

  // 新增：检查是否需要自动连接
  private checkAutoConnect() {
    // 延迟检查，确保store已经初始化
    setTimeout(() => {
      const token = getToken()
      if (token && this.autoConnectOnInit && !this.isConnected) {
        console.log('检测到已登录状态，自动建立WebSocket连接')
        this.connect()
      }
    }, 1000)
  }

  private setupEventHandlers() {
    if (!this.client) return

    this.client.onConnect = (frame) => {
      console.log('WebSocket连接成功:', frame)
      this.isConnected = true
      this.reconnectAttempts = 0
      this.subscribeToUserReminders()
      this.subscribeToHealthStatus() // 新增：订阅健康状态

      // 只在手动连接时显示通知，自动重连时不显示
      if (this.reconnectAttempts === 0) {
        ElNotification({
          title: '连接成功',
          message: 'WebSocket连接已建立',
          type: 'success',
          duration: 2000
        })
      }
    }

    this.client.onDisconnect = (frame) => {
      console.log('WebSocket连接断开:', frame)
      this.isConnected = false
      this.subscriptions.clear()

      // 如果有token且不是主动断开，则尝试重连
      // const token = getToken()
      const token = getTokenB()
      if (token && this.autoConnectOnInit) {
        console.log('检测到意外断开，准备重连...')
        this.handleConnectionError()
      }
    }

    this.client.onStompError = (frame) => {
      console.error('STOMP错误:', frame)
      this.handleConnectionError()
    }

    this.client.onWebSocketError = (error) => {
      console.error('WebSocket错误:', error)
      this.handleConnectionError()
    }
  }

  private handleConnectionError() {
    // 检查是否还有有效token
    // const token = getToken()
    // const token = userStore.tokenB
    const token = getTokenB()
    if (!token) {
      console.log('未找到有效token，停止重连')
      return
    }

    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++
      console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`)

      setTimeout(() => {
        this.connect()
      }, this.reconnectDelay * this.reconnectAttempts)
    } else {
      ElNotification({
        title: '连接失败',
        message: 'WebSocket连接失败，请检查网络或刷新页面重试',
        type: 'error',
        duration: 0
      })
    }
  }

  public connect(wsUrl: string = `/ws-reminders`) {
    if (this.isConnected || !this.client) return

    const token = getTokenB() // 优先使用store中的token，fallback到cookie

    if (!token) {
      console.warn('未找到认证令牌，无法建立WebSocket连接')
      return
    }

    // 设置SockJS连接
    this.client.webSocketFactory = () => {
      return new SockJS(wsUrl) // 直接使用导入的SockJS
    }

    // 设置认证头
    this.client.connectHeaders = {
      Authorization: token
    }

    console.log('正在连接WebSocket...', wsUrl)
    this.client.activate()
  }

  public disconnect(manual: boolean = false) {
    if (manual) {
      // 手动断开时，禁用自动重连
      this.autoConnectOnInit = false
    }

    if (this.client && this.isConnected) {
      this.client.deactivate()
      this.isConnected = false
      this.subscriptions.clear()
      console.log('WebSocket连接已断开')
    }
  }

  // 新增：启用自动连接
  public enableAutoConnect() {
    this.autoConnectOnInit = true
  }

  // 新增：禁用自动连接
  public disableAutoConnect() {
    this.autoConnectOnInit = false
  }

  private subscribeToUserReminders() {
    const userStore = useUserStore()
    const userId = userStore.userId

    if (!userId || !this.client) {
      // 如果userId不存在，尝试获取用户信息
      if (getToken()) {
        userStore.getInfo().then(() => {
          // 获取用户信息后重新尝试订阅
          setTimeout(() => {
            this.subscribeToUserReminders()
            this.subscribeToHealthStatus() // 同时重新订阅健康状态
          }, 500)
        })
      }
      return
    }

    const destination = `/topic/reminders/${userId}`

    const subscription = this.client.subscribe(destination, (message) => {
      try {
        const reminderData: WebSocketMessage = JSON.parse(message.body)
        this.handleReminderMessage(reminderData)
      } catch (error) {
        console.error('解析提醒消息失败:', error)
      }
    })

    this.subscriptions.set(`reminders-${userId}`, subscription)
    console.log(`已订阅用户提醒: ${destination}`)
  }

  // 新增：订阅健康状态
  private subscribeToHealthStatus() {
    const userStore = useUserStore()
    const userId = userStore.userId

    if (!userId || !this.client) {
      return
    }

    const destination = `/topic/health/${userId}`

    const subscription = this.client.subscribe(destination, (message) => {
      try {
        const healthData: HealthMessage = JSON.parse(message.body)
        this.handleHealthMessage(healthData)
      } catch (error) {
        console.error('解析健康状态消息失败:', error)
      }
    })

    this.subscriptions.set(`health-${userId}`, subscription)
    console.log(`已订阅健康状态: ${destination}`)
  }

  private handleReminderMessage(message: WebSocketMessage) {
    console.log('收到提醒消息:', message)

    // 显示通知
    ElNotification({
      title: message.title,
      message: message.description,
      type: 'warning',
      duration: 5000,
      showClose: true,
      onClick: () => {
        // 可以在这里处理点击通知的逻辑
        console.log('用户点击了提醒通知')
      }
    })

    // 触发自定义事件，让其他组件可以监听
    window.dispatchEvent(
      new CustomEvent('reminder-received', {
        detail: message
      })
    )
  }

  // 新增：处理健康状态消息
  private handleHealthMessage(message: HealthMessage) {
    console.log('收到健康状态消息:', message)

    // 显示机器人失联警告通知
    ElNotification({
      title: '机器人状态警告',
      message: '机器人可能失联！请检查设备连接状态。',
      type: 'error',
      duration: 0, // 不自动关闭
      showClose: true,
      onClick: () => {
        console.log('用户点击了机器人失联通知')
      }
    })

    // 触发自定义事件，让其他组件可以监听
    window.dispatchEvent(
      new CustomEvent('robot-health-alert', {
        detail: message
      })
    )
  }

  public sendMessage(destination: string, message: any) {
    if (!this.isConnected || !this.client) {
      console.warn('WebSocket未连接，无法发送消息')
      return
    }

    this.client.publish({
      destination,
      body: JSON.stringify(message)
    })
  }

  public getConnectionStatus() {
    return this.isConnected
  }

  // 新增：重置重连计数器
  public resetReconnectAttempts() {
    this.reconnectAttempts = 0
  }
}

// 创建单例实例
export const webSocketService = new WebSocketService()

// 监听页面可见性变化，当页面重新可见时检查连接状态
document.addEventListener('visibilitychange', () => {
  if (!document.hidden && getToken() && !webSocketService.getConnectionStatus()) {
    console.log('页面重新可见，检查WebSocket连接状态')
    webSocketService.resetReconnectAttempts()
    webSocketService.connect()
  }
})
